﻿using BarcodeDelay.bean;
using BarcodeDelay.utility;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BarcodeDelay.business
{
    public class DelayAnaHelper
    {
        private string m_strBacodes = "";
        private ArrayList m_arListArrivalBarcodes = new ArrayList();
        private ArrayList m_arListDepBarcodes = new ArrayList();
        private ArrayList m_arListFruitBarcodes = new ArrayList();
        private int totalQueryCount = 0;
        public Hashtable m_ht_arrival_BarCodes = new Hashtable();
        public Hashtable m_ht_departure_BarCodes = new Hashtable();
        public Hashtable m_ht_fruit_BarCodes = new Hashtable();

        public Hashtable m_ht_far_province = new Hashtable();
        public event Action DoneArriAnay;
        public event Action DoneDepAnay;
        public event Action DoneFruitAnay;
        public event Action DoneArrOrDepAnay;

        

        private StreamWriter swb = null;
        FileStream bFile = null;
        private DateTime dtLastRefreshDep = new DateTime();
        private DateTime dtLastRefreshArr = new DateTime();
        private DateTime dtLastRefreshFruit = new DateTime();
        private ArrayList arListResultDep = new ArrayList();
        private static DelayAnaHelper instance;
        public static DelayAnaHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new DelayAnaHelper();
                }
                return instance;
            }
        }
        private Thread fThreadDep = null;
        private Thread fThreadArr = null;
        private Thread fThreadFruit = null;
        public void BeginAnalyThread(ArrayList arListBarCodes,string anayType)
        {
            try
            {
                initLog();
                if (anayType.Contains("arrival"))
                {
                    m_arListArrivalBarcodes = arListBarCodes;
                    fThreadArr = new Thread(new ThreadStart(parseArrivalBarcodes));//进港分析 开辟一个新的线程
                    fThreadArr.IsBackground = true;
                    fThreadArr.Start();
                }
                else if (anayType.Contains("departure"))
                {
                    m_ht_departure_BarCodes.Clear();
                    if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                    {
                        fThreadDep.Abort();
                        System.Threading.Thread.Sleep(50);
                    }
                    if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                    {
                        while (fThreadDep.ThreadState != ThreadState.Aborted)
                        {
                            //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                            Thread.Sleep(100);
                        }
                    }
                        
                    
                    m_arListDepBarcodes = arListBarCodes;
                    fThreadDep = new Thread(new ThreadStart(parseDepartureBarcodes));//出港分析 开辟一个新的线程
                    fThreadDep.IsBackground = true;
                    fThreadDep.Start();
                }
                else
                {
                    m_arListFruitBarcodes = arListBarCodes;
                    fThreadFruit = new Thread(new ThreadStart(parseFruitBarcodes));//水果生鲜分析 开辟一个新的线程
                    fThreadFruit.Start();
                }

               
                initFarProvince();


            }
            catch(Exception ex)
            {

            }
            
            
        }

        public void stopThread()
        {
            try
            {
              
            }
            catch(Exception ex)
            {

            }
        }

        private void initFarProvince()
        {
            m_ht_far_province["新疆"] = "";
            m_ht_far_province["西藏"] = "";
            m_ht_far_province["内蒙古"] = "";
            m_ht_far_province["黑龙江"] = "";
            m_ht_far_province["青海"] = "";
            m_ht_far_province["云南"] = "";
            m_ht_far_province["甘肃"] = "";
        }
        private void initLog()
        {
            try
            {
                string dir = System.Environment.CurrentDirectory;
                bFile = new FileStream(dir+"\\error.txt", FileMode.Create);
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                    swb.WriteLine("begin");
                   
                }
            }
            catch(Exception ex)
            {

            }
            
        }

        private void getMySiteInfo()
        {
            try
            {

            }
            catch(Exception ex)
            {

            }
        }
        #region 查询面单
        public void queryWayBill(Hashtable htQuery,string barcode)
        {
            try
            {
                string strUrl = "http://" + StoParams.Instance.queryUrl;
                string strAppend = "";
                strAppend = strAppend + barcode + "%2C";
                System.DateTime dtBegin = System.DateTime.Now;
                strUrl = strUrl + "?billCodes=" + strAppend.Substring(0, strAppend.Length - 3);
                string postData = "{\"billCodes\":" + "\"" + "" + "\"}";
                string res = HttpClient.HttpUtil.Instance.GetPage(strUrl, postData);

                JObject jsonObj = (JObject)JsonConvert.DeserializeObject(res);
                JToken record = (JToken)jsonObj["ResultValue"];
                JArray jar = (JArray)JsonConvert.DeserializeObject(record.ToString());
                string strStatus = "";
                string strRunTime = "";
                string strBarcode = "";


                for (int i = 0; i < jar.Count; i++)
                {

                    try
                    {
                        JObject jason = JObject.Parse(jar[i].ToString());
                        string scanList = jason["ScanList"].ToString();
                        JArray jarScanList = (JArray)JsonConvert.DeserializeObject(scanList.ToString());
                        bool isUserFinished = false;
                        JToken status = (JToken)jason["Status"];
                        JToken barCode = (JToken)jason["Id"];
                        JToken runTime = (JToken)jason["RunTime"];
                        if (runTime == null || runTime.ToString() == "")
                        {
                            break;
                        }
                        string strDay = runTime.ToString();
                        strDay = strDay.Substring(0, strDay.IndexOf("天"));

                        if (status != null)
                        {
                            strStatus = status.ToString();
                        }
                        if (runTime != null)
                        {
                            strRunTime = runTime.ToString();
                        }
                        if (barCode != null)
                        {
                            strBarcode = barCode.ToString();
                        }
                        else
                        {
                            continue;
                        }


                        RoadInfo roadInfo = new bean.RoadInfo();
                        roadInfo.runTime = runTime.ToString();
                        roadInfo.wayBillNo = strBarcode;
                        roadInfo.lastScanStatus = strStatus;
                        for (int m = 0; m < jarScanList.Count; m++)
                        {
                            JObject scanInfo = JObject.Parse(jarScanList[m].ToString());
                            string scanType = scanInfo["ScanType"].ToString();
                            string ScanDate = scanInfo["ScanDate"].ToString();
                            string UploadSiteName = scanInfo["UploadSiteName"].ToString();
                            string PreOrNext = scanInfo["PreOrNext"].ToString();
                            string Memo = scanInfo["Memo"].ToString();
                            MemInfo memInfo = new bean.MemInfo();
                            memInfo.memMsg = Memo;
                            memInfo.scanType = scanType;
                            memInfo.scanTime = ScanDate;
                            roadInfo.arListMems.Add(memInfo);                            
                            
                        }
                        htQuery[strBarcode] = roadInfo;
                    }
                    catch (Exception ex)
                    {

                    }

                }//for

            }
            catch(Exception ex)
            {

            }

        }
        #endregion



        #region 生鲜件处理流程
        private void parseFruitBarcodes()
        {
            string curBarcode = "";
            try
            {
                ArrayList arListBarcodes = new ArrayList();
                ArrayList arListTmp = new ArrayList();
                for (int i = 0; i < m_arListFruitBarcodes.Count; i++)
                {
                    string barcode = m_arListFruitBarcodes[i].ToString();
                    if (i > 0 && (i + 1) % 20 == 0)
                    {
                        arListTmp.Add(barcode);
                        arListBarcodes.Add(arListTmp.Clone());
                        arListTmp.Clear();
                    }
                    else
                    {
                        arListTmp.Add(barcode);
                    }
                }
                if (arListTmp.Count > 0)
                {
                    arListBarcodes.Add(arListTmp.Clone());
                    arListTmp.Clear();
                }

                int intProcess = 0;
                int sumQueryTime = 0;
                int avgQueryTime = 2;
                int priorBarCodeCount = 0;
                foreach (ArrayList arListBarcode in arListBarcodes)
                {
                    intProcess++;
                    string strLeftTime = UtilityHelp.Instance.getLeftTime(arListBarcodes.Count, intProcess, avgQueryTime);
                    Program.m_frmain.SetTextMessage(intProcess, arListBarcodes.Count, strLeftTime);
                    string strUrl = "http://" + StoParams.Instance.queryUrl;
                    string strAppend = "";
                    foreach (string strBarCode in arListBarcode)
                    {
                        strAppend = strAppend + strBarCode + "%2C";
                    }
                    System.DateTime dtBegin = System.DateTime.Now;
                    strUrl = strUrl + "?billCodes=" + strAppend.Substring(0, strAppend.Length - 3);
                    string postData = "{\"billCodes\":" + "\"" + "" + "\"}";
                    string res = HttpClient.HttpUtil.Instance.GetPage(strUrl, postData);
                    System.DateTime dtEnd = System.DateTime.Now;
                    TimeSpan tsSpend = dtEnd - dtBegin;
                    int oneQuery = Convert.ToInt32(tsSpend.TotalSeconds);
                    sumQueryTime = sumQueryTime + oneQuery;
                    avgQueryTime = Convert.ToInt32(sumQueryTime / intProcess);

                    JObject jsonObj = (JObject)JsonConvert.DeserializeObject(res);
                    JToken record = (JToken)jsonObj["ResultValue"];
                    JArray jar = (JArray)JsonConvert.DeserializeObject(record.ToString());
                    string strStatus = "";
                    string strRunTime = "";
                    string strBarcode = "";


                    for (int i = 0; i < jar.Count; i++)
                    {

                        try
                        {
                            JObject jason = JObject.Parse(jar[i].ToString());
                            string scanList = jason["ScanList"].ToString();
                            JArray jarScanList = (JArray)JsonConvert.DeserializeObject(scanList.ToString());
                            bool isUserFinished = false;
                            JToken status = (JToken)jason["Status"];
                            JToken barCode = (JToken)jason["Id"];
                            JToken runTime = (JToken)jason["RunTime"];
                            if (runTime == null || runTime.ToString() == "")
                            {
                                break;
                            }
                            string strDay = runTime.ToString();
                            strDay = strDay.Substring(0, strDay.IndexOf("天"));

                            if (status != null)
                            {
                                strStatus = status.ToString();
                            }
                            if (runTime != null)
                            {
                                strRunTime = runTime.ToString();
                            }
                            if (barCode != null)
                            {
                                strBarcode = barCode.ToString();
                            }
                            else
                            {
                                continue;
                            }


                            RoadInfo roadInfo = new bean.RoadInfo();
                            roadInfo.runTime = runTime.ToString();
                            roadInfo.wayBillNo = strBarcode;
                            curBarcode = strBarcode;
                            roadInfo.lastScanStatus = strStatus;
                            for (int m = 0; m < jarScanList.Count; m++)
                            {
                                JObject scanInfo = JObject.Parse(jarScanList[m].ToString());
                                string scanType = scanInfo["ScanType"].ToString();
                                string ScanDate = scanInfo["ScanDate"].ToString();
                                string UploadSiteName = scanInfo["UploadSiteName"].ToString();
                                string PreOrNext = scanInfo["PreOrNext"].ToString();
                                string Memo = scanInfo["Memo"].ToString();
                                MemInfo memInfo = new bean.MemInfo();
                                memInfo.memMsg = Memo;
                                memInfo.scanType = scanType;
                                memInfo.scanTime = ScanDate;
                                roadInfo.arListMems.Add(memInfo);
                                if (PreOrNext == StoParams.Instance.register_site && UploadSiteName == StoParams.Instance.arrival_priorSite)
                                {
                                    DateTime dtScanTime = Convert.ToDateTime(ScanDate);
                                    TimeSpan ts = dtScanTime.TimeOfDay;
                                    TimeSpan tsEndTime = DateTime.Parse(StoParams.Instance.arrival_priorSite_SacnEndTime).TimeOfDay;
                                    if (ts < tsEndTime)
                                    {
                                        roadInfo.todayFinish = true;
                                        string strDate = dtScanTime.ToString("yyyy-MM-dd") + " " + "23:59:59";
                                        roadInfo.endLineTime = strDate;
                                    }
                                    roadInfo.arriveSendToSiteTime = ScanDate;
                                }

                                if (scanType.Contains("签收"))
                                {
                                    if (roadInfo.donePackTime.Length > 0)
                                    {
                                        roadInfo.doubleFinished = true;
                                    }
                                    else
                                    {
                                        roadInfo.donePackTime = ScanDate;
                                    }

                                }
                                if (Memo.Contains("派送不成功"))
                                {
                                    break;
                                }
                                if (m == 0)
                                {
                                    roadInfo.lastSiteScanDate = ScanDate;
                                    if (scanType.ToString().Contains("运输中"))
                                    {
                                        roadInfo.lastSiteName = PreOrNext;
                                    }
                                    else
                                    {
                                        roadInfo.lastSiteName = UploadSiteName;
                                    }

                                }
                                if (scanType.ToString().Contains("签收"))
                                {
                                    roadInfo.lastSiteScanDate = "";
                                    if (roadInfo.donePackTime == "")
                                    {
                                        roadInfo.donePackTime = ScanDate;
                                    }
                                }



                                if (scanType.ToString().Contains("派送"))
                                {

                                    UtilityHelp.Instance.fillYizhanOrAssignTime(roadInfo, Memo, ScanDate, scanType);
                                    roadInfo.arrivalBeglongSite = UploadSiteName;

                                }
                                if (scanType.ToString().Contains("运输中"))
                                {
                                    if (roadInfo.arriveSiteTime == "")
                                    {
                                        roadInfo.arriveSiteTime = ScanDate;
                                    }
                                }
                            }
                            //if (isArrivalPackDelayed(roadInfo))
                            {
                                isArrivalPackDelayed(roadInfo);
                                m_ht_fruit_BarCodes[strBarcode] = roadInfo;
                            }
                        }
                        catch (Exception ex)
                        {

                        }

                    }//for

                }
                if (priorBarCodeCount != m_ht_fruit_BarCodes.Count)
                {
                    DateTime dtNow = System.DateTime.Now;
                    TimeSpan ts = dtNow - dtLastRefreshFruit;
                    priorBarCodeCount = m_ht_fruit_BarCodes.Count;
                    DoneFruitAnay.Invoke();
                    dtLastRefreshDep = dtNow;
                   
                }


            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("发生异常，条码为" + curBarcode);
            }
        }
        #endregion


        private void parseDepartureBarcodes()
        {
            int totalDelays = 0;
            int queryServerResTime = 0;
            try
            {
                totalQueryCount = 0;
                m_strBacodes = m_strBacodes.Replace("\n", " ");
                string[] arr = m_strBacodes.Split(' ');
                ArrayList arListBarcodes = new ArrayList();
                ArrayList arListTmp = new ArrayList();
                for (int i = 0; i < m_arListDepBarcodes.Count; i++)
                {
                    string barcode = m_arListDepBarcodes[i].ToString();
                    if (i > 0 && (i + 1) % 10 == 0)
                    {
                        arListTmp.Add(barcode);
                        arListBarcodes.Add(arListTmp.Clone());
                        arListTmp.Clear();
                    }
                    else
                    {
                        arListTmp.Add(barcode);
                    }
                }
                if (arListTmp.Count > 0)
                {
                    arListBarcodes.Add(arListTmp.Clone());
                    arListTmp.Clear();
                }

                int intProcess = 0;
                int sumQueryTime = 0;
                int avgQueryTime = 2;
                int priorBarCodeCount = 0;
                ArrayList arListDepResultTmp = new ArrayList();
                foreach (ArrayList arListBarcode in arListBarcodes)
                {
                    intProcess++;
                    string strLeftTime = UtilityHelp.Instance.getLeftTime(arListBarcodes.Count, intProcess, avgQueryTime);
                    Program.m_frmain.SetTextMessage(intProcess, arListBarcodes.Count, strLeftTime);
             
                    string strUrl = "http://"+StoParams.Instance.queryUrl;
                    string strAppend = "";
                    foreach (string strBarCode in arListBarcode)
                    {
                        totalQueryCount = totalQueryCount + 1;
                        strAppend = strAppend + strBarCode + "%2C";
                    }
                    System.DateTime dtBegin = System.DateTime.Now;
                    strUrl = strUrl + "?billCodes=" + strAppend.Substring(0, strAppend.Length - 3);
                    string postData = "{\"billCodes\":" + "\"" + "" + "\"}";
                    
                    string res = HttpClient.HttpUtil.Instance.GetPage(strUrl, postData);
                    if (res.Length > 300)
                    {
                        queryServerResTime++;
                    }
                    else
                    {
                        continue;
                    }
                    lock (Program.obj_left_count)
                    {
                        StoParams.Instance.day_left = StoParams.Instance.day_left - arListBarcode.Count;
                        if (StoParams.Instance.day_left <= 0)
                        {
                            StoParams.Instance.day_left = 0;
                            break;
                        }
                    }
                    System.DateTime dtEnd = System.DateTime.Now;
                    TimeSpan tsSpend = dtEnd - dtBegin;
                    int oneQuery = Convert.ToInt32(tsSpend.TotalSeconds);
                    sumQueryTime = sumQueryTime + oneQuery;
                    avgQueryTime = Convert.ToInt32(sumQueryTime / intProcess);
                    JObject jsonObj = (JObject)JsonConvert.DeserializeObject(res);
                    JToken record = (JToken)jsonObj["ResultValue"];
                    JArray jar = (JArray)JsonConvert.DeserializeObject(record.ToString());
                    string strStatus = "";
                    string strRunTime = "";
                    string strBarcode = "";
                    

                    for (int i = 0; i < jar.Count; i++)
                    {
                        try
                        {
                            JObject jason = JObject.Parse(jar[i].ToString());
                            string scanList = jason["ScanList"].ToString();
                            JArray jarScanList = (JArray)JsonConvert.DeserializeObject(scanList.ToString());
                            bool isUserFinished = false;
                            JToken status = (JToken)jason["Status"];
                            JToken barCode = (JToken)jason["Id"];
                            JToken runTime = (JToken)jason["RunTime"];
                            if (runTime == null || runTime.ToString() == "")
                            {
                                break;
                            }
                            string strDay = runTime.ToString();
                            strDay = strDay.Substring(0, strDay.IndexOf("天"));

                            if (status != null)
                            {
                                strStatus = status.ToString();
                            }
                            if (runTime != null)
                            {
                                strRunTime = runTime.ToString();
                            }
                            if (barCode != null)
                            {
                                strBarcode = barCode.ToString();
                            }
                            else
                            {
                                continue;
                            }


                            RoadInfo roadInfo = new bean.RoadInfo();
                            roadInfo.runTime = runTime.ToString();
                            roadInfo.wayBillNo = strBarcode;
                            roadInfo.lastScanStatus = strStatus;
                            bool isFirstArriBingo = false;
                            string priorArrivalMemo = "";
                            if (jarScanList.Count > 3)
                            {
                                JObject scanInfo = JObject.Parse(jarScanList[0].ToString());
                                string MemoFirst = scanInfo["Memo"].ToString();
                                JObject scanInfo1 = JObject.Parse(jarScanList[1].ToString());
                                string MemoSecond = scanInfo1["Memo"].ToString();
                                JObject scanInfo2 = JObject.Parse(jarScanList[2].ToString());
                                string MemoThird = scanInfo2["Memo"].ToString();
                                string scanType = scanInfo["ScanType"].ToString();
                                string ScanDate = scanInfo["ScanDate"].ToString();
                                string UploadSiteName = scanInfo["UploadSiteName"].ToString();
                                string PreOrNext = scanInfo["PreOrNext"].ToString();
                                string Memo = scanInfo["Memo"].ToString();


                                string scanType2 = scanInfo2["ScanType"].ToString();


                                /*if (scanType== "已签收"&& scanType2== "已签收")
                                {
                                    if(MemoSecond.Contains("代收"))
                                    {
                                        swb.WriteLine("疑似件: " + strBarcode);
                                    }
                                    else
                                    {
                                        int a = 0;
                                    }

                                }*/

                                if (MemoThird.Contains("已签收，签收人")&&MemoThird.Contains("韵达快递超市"))
                                {
                                    if(MemoFirst.Contains("韵达快递超市")&& MemoSecond.Contains("韵达快递超市"))
                                    {
                                        swb.WriteLine("韵达快递超市: " + strBarcode);
                                        jarScanList.RemoveAt(0);
                                        jarScanList.RemoveAt(0);
                                    }
                                }
                                /*if (MemoThird.Contains("已签收，签收人") && MemoThird.Contains("妈妈驿站"))
                                {
                                    if (MemoSecond.Contains("妈妈驿站")&& MemoSecond.Contains("代收"))
                                    {
                                        swb.WriteLine("妈妈驿站: " + strBarcode);
                                        jarScanList.RemoveAt(0);
                                        jarScanList.RemoveAt(0);
                                    }
                                }*/


                            }

                            for (int m = 0; m < jarScanList.Count; m++)
                            {
                                JObject scanInfo = JObject.Parse(jarScanList[m].ToString());
                                string scanType = scanInfo["ScanType"].ToString();
                                string ScanDate = scanInfo["ScanDate"].ToString();
                                string UploadSiteName = scanInfo["UploadSiteName"].ToString();
                                string PreOrNext = scanInfo["PreOrNext"].ToString();
                                string Memo = scanInfo["Memo"].ToString(); 
                                MemInfo memInfo = new bean.MemInfo();
                                memInfo.memMsg = Memo;
                                memInfo.scanType = scanType;
                                memInfo.scanTime = ScanDate;
                                memInfo.preOrNext = PreOrNext;
                                memInfo.uploadSiteName = UploadSiteName;
                                roadInfo.arListMems.Add(memInfo);
                                if(Memo.Contains("快递员取出"))
                                {
                                    roadInfo.isGetOutByDeliver = true;
                                }
                                if(Memo.Contains("超派件")&&Memo.Contains("客户自取"))
                                {
                                    roadInfo.isChaoPaiPackage = true;
                                    break;
                                }


                                if (UploadSiteName == StoParams.Instance.register_site && Memo.Contains("发往"))
                                {
                                    DateTime dtScanTime = Convert.ToDateTime(ScanDate);
                                    if (roadInfo.depMySiteSendTime == "")
                                    {
                                        roadInfo.depMySiteSendTime = ScanDate;
                                    }
                           
                                }

                                if (UploadSiteName == StoParams.Instance.register_site && scanType.Contains("已揽收"))
                                {
                                    DateTime dtScanTime = Convert.ToDateTime(ScanDate);
                                    roadInfo.lanshouTime = ScanDate;

                                }

                                if (UploadSiteName == StoParams.Instance.register_site && scanType.Contains("已揽收")||
                                    UploadSiteName == StoParams.Instance.register_site && scanType.Contains("运输中"))
                                {
                                    if (m > jarScanList.Count - 5)
                                    {
                                        roadInfo.isSendFromMySite = true;
                                    }
                                }

                                if(scanType.Contains("退件")|| scanType.Contains("退回件"))
                                {
                                    roadInfo.isReturnPackage = true;
                                }

                                if (scanType.Contains("签收")||Memo.StartsWith("已签收")||Memo.Contains("派件已【签收】") || Memo.Contains("派件已签收"))
                                {
                                    roadInfo.donePackTime = ScanDate;
                                    if (UploadSiteName == StoParams.Instance.register_site)
                                    {
                                        roadInfo.isDepRecvByMeself = true;
                                    }

                                }
                                if (Utility.isWeekendDeleverPackage(Memo)||Memo.Contains("明日送"))
                                {
                                    roadInfo.isErrorPackage = true;
                                    roadInfo.errorScanTime = ScanDate;
                                    roadInfo.errorScanTimes++;
                                }

                                if (Memo.Contains("建包错发件")||Memo.Contains("网络错分件"))
                                {
                                    roadInfo.isSortWrong = true;
                                    roadInfo.sortWrongTime = ScanDate;
                                }

                                if (UploadSiteName.Contains("转运中心")|| UploadSiteName.Contains("集散") || UploadSiteName.Contains("航空部"))
                                {
                                    roadInfo.isDelverByZy = true;
                                }
                                if(m>=1)
                                {
                                    if (!isFirstArriBingo&& !StoParams.Instance.ht_sto_province_day.ContainsKey(roadInfo.province))
                                    {
                                        if(UploadSiteName.Length>1)
                                        {
                                            roadInfo.province = UtilityHelp.Instance.getFullProvince(UploadSiteName.Substring(0, 2));
                                            roadInfo.province = UtilityHelp.Instance.getActProvince(roadInfo.province);
                                            if (StoParams.Instance.ht_sto_province_day.ContainsKey(roadInfo.province))
                                            {
                                                isFirstArriBingo = true;
                                            }
                                        }
                                        
                                    }
                                }
                               

                                if (m == 0)
                                {

                                    if (UploadSiteName.Length > 2)
                                    {
                                        if(UploadSiteName.Length>1)
                                        {
                                            roadInfo.province = UtilityHelp.Instance.getFullProvince(UploadSiteName.Substring(0, 2));
                                            roadInfo.province = UtilityHelp.Instance.getActProvince(roadInfo.province);
                                        }
                                        
                                    }
                                    roadInfo.lastSiteScanDate = ScanDate;
                                    roadInfo.lastSiteStatus = scanType.ToString();
                                    if (scanType.ToString().Contains("运输中"))
                                    {
                                        if(PreOrNext!=null&& PreOrNext.Length>2)
                                        {
                                            roadInfo.province = UtilityHelp.Instance.getFullProvince(PreOrNext.Substring(0, 2));
                                            roadInfo.province = UtilityHelp.Instance.getActProvince(roadInfo.province);
                                        }
                                        else
                                        {
                                            string province = UtilityHelp.Instance.getNextDesProvince(Memo);
                                            province = UtilityHelp.Instance.getActProvince(province);
                                            if (province!=""&& (Memo.Contains("转运中心")|| Memo.Contains("集散中心")))
                                            {
                                                roadInfo.province = province;
                                            }

                                        }
                                        if(PreOrNext!="")
                                        {
                                            roadInfo.lastSiteName = PreOrNext;
                                        }
                                        else
                                        {
                                            roadInfo.lastSiteName = UploadSiteName;
                                        }
                                        
                                    }
                                    else
                                    {
                                        roadInfo.lastSiteName = UploadSiteName;
                                    }

                                }
                                if (scanType.ToString().Contains("签收") || Memo.StartsWith("已签收")||Memo.Contains("已签收，签收人凭取货码签收"))
                                {
                                    roadInfo.lastSiteScanDate = "";
                                    if (roadInfo.donePackTime == "")
                                    {
                                        roadInfo.donePackTime = ScanDate;
                                    }
                                }

                                if (scanType.ToString().Contains("派送"))
                                {
                                    UtilityHelp.Instance.fillYizhanOrAssignTime(roadInfo, Memo, ScanDate,scanType);
                                }
                                if (scanType.ToString().Contains("运输中"))
                                {
                                    if(priorArrivalMemo!=""&& priorArrivalMemo== Memo&& m >1&&m<=6 && (Memo.StartsWith("已到达")||Memo.StartsWith("快件已到达")))
                                    {
                                        roadInfo.arriveSiteTime = ScanDate;
                                    }
                                    if (roadInfo.arriveSiteTime == ""&&(Memo.StartsWith("已到达")|| Memo.StartsWith("快件已到达")))
                                    {
                                        roadInfo.arriveSiteTime = ScanDate;
                                        priorArrivalMemo = Memo;
                                    }
                                }
                            }
                
                            if (isDepPackDelayed(roadInfo))
                            {
                                totalDelays++;
                                arListDepResultTmp.Add(roadInfo.wayBillNo + "," + roadInfo.strErrorMsg + "," + roadInfo.lastSiteName);
                                //lock (Program.obj_dep_table)
                                {
                                    m_ht_departure_BarCodes[strBarcode] = roadInfo;                                  

                                }
                                
                            }
                        }
                        catch(Exception ex)
                        {

                        }                      

                    }//for
                    if(priorBarCodeCount!= m_ht_departure_BarCodes.Count)
                    {
                        DateTime dtNow = System.DateTime.Now;
                        TimeSpan ts = dtNow - dtLastRefreshDep;
                        priorBarCodeCount = m_ht_departure_BarCodes.Count;
                        if (ts.TotalSeconds>3)
                        {
                            lock (Program.obj_dep_table)
                            {
                                DoneDepAnay.Invoke();

                                DoneArrOrDepAnay();
                            }
                            dtLastRefreshDep = dtNow;

                        }                       


                    }
                    if(totalQueryCount>=200)
                    {
                        ArrayList arListT = new ArrayList();
                        arListT = (ArrayList)arListDepResultTmp.Clone();
                        ResultBean resultBean = new ResultBean();
                        //resultBean.countTime = totalQueryCount;
                        //resultBean.arList = arListT;
                        updateQueryCount(resultBean);
                        arListDepResultTmp.Clear();
                        totalQueryCount = 0;
                    }
                    


                }//foreach
                System.Threading.Thread.Sleep(1000);
                DoneDepAnay.Invoke();
                DoneArrOrDepAnay();
                if(totalQueryCount>0)
                {
                    ArrayList arListT = new ArrayList();
                    arListT = (ArrayList)arListDepResultTmp.Clone();
                    ResultBean resultBean = new ResultBean();
                    //resultBean.countTime = totalQueryCount;
                    //resultBean.arList = arListT;
                    updateQueryCount(resultBean);
                    totalQueryCount = 0;
                }
                

            }
            catch (Exception ex)
            {

            }
            int tiot = queryServerResTime;


        }


        private void updateQueryCount(ResultBean result)
        {
            try
            {
                Thread  fThread = new Thread(new ParameterizedThreadStart(updateServer));
                fThread.Start(result);
            }
            catch(Exception ex)
            {

            }
        }
        private void updateServer(object obj)
        {
            try
            {
                ResultBean result = (ResultBean)obj;
                //MemberInfo.Instance.setUseCountTime(result.countTime, result.arList);
            }
            catch(Exception ex)
            {

            }
        }

        private void parseArrivalBarcodes()
        {
            string curBarcode = "";
            int totalQueryCount = 0;
            try
            {   
                m_strBacodes = m_strBacodes.Replace("\n", " ");
                string[] arr = m_strBacodes.Split(' ');
                ArrayList arListBarcodes = new ArrayList();
                ArrayList arListTmp = new ArrayList();
                for (int i = 0; i < m_arListArrivalBarcodes.Count; i++)
                {
                    string barcode = m_arListArrivalBarcodes[i].ToString();
                    if (i > 0 && (i + 1) % 10 == 0)
                    {
                        arListTmp.Add(barcode);
                        arListBarcodes.Add(arListTmp.Clone());
                        arListTmp.Clear();
                        //arListTmp.Add(barcode);
                    }
                    else
                    {
                        arListTmp.Add(barcode);
                    }
                }
                if (arListTmp.Count > 0)
                {
                    arListBarcodes.Add(arListTmp.Clone());
                    arListTmp.Clear();
                }

                int intProcess = 0;
                int sumQueryTime = 0;
                int avgQueryTime = 2;
                int priorBarCodeCount = 0;
                ArrayList arListArriResultTmp = new ArrayList();
                foreach (ArrayList arListBarcode in arListBarcodes)
                {
                    intProcess++;
                    string strLeftTime=UtilityHelp.Instance.getLeftTime(arListBarcodes.Count, intProcess, avgQueryTime);
                    Program.m_frmain.SetTextMessage(intProcess, arListBarcodes.Count, strLeftTime);
                    string strUrl = "http://" + StoParams.Instance.queryUrl;
                    string strAppend = "";
                    foreach (string strBarCode in arListBarcode)
                    {
                        strAppend = strAppend + strBarCode + "%2C";
                        totalQueryCount++;
                    }
                    System.DateTime dtBegin = System.DateTime.Now;
                    strUrl = strUrl + "?billCodes=" + strAppend.Substring(0, strAppend.Length - 3);
                    string postData = "{\"billCodes\":" + "\"" + "" + "\"}";
                    string res = HttpClient.HttpUtil.Instance.GetPage(strUrl, postData);
                    lock(Program.obj_left_count)
                    {
                        StoParams.Instance.day_left = StoParams.Instance.day_left - arListBarcode.Count;
                        if (StoParams.Instance.day_left <= 0)
                        {
                            StoParams.Instance.day_left = 0;
                            break;
                        }
                    }
                    

                    System.DateTime dtEnd = System.DateTime.Now;
                    TimeSpan tsSpend = dtEnd - dtBegin;
                    int oneQuery = Convert.ToInt32(tsSpend.TotalSeconds);
                    sumQueryTime = sumQueryTime + oneQuery;
                    avgQueryTime = Convert.ToInt32(sumQueryTime / intProcess);

                    JObject jsonObj = (JObject)JsonConvert.DeserializeObject(res);
                    JToken record = (JToken)jsonObj["ResultValue"];
                    JArray jar = (JArray)JsonConvert.DeserializeObject(record.ToString());
                    string strStatus = "";
                    string strRunTime = "";
                    string strBarcode = "";


                    for (int i = 0; i < jar.Count; i++)
                    {
     
                        try
                        {
                            JObject jason = JObject.Parse(jar[i].ToString());
                            string scanList = jason["ScanList"].ToString();
                            JArray jarScanList = (JArray)JsonConvert.DeserializeObject(scanList.ToString());
                            bool isUserFinished = false;
                            JToken status = (JToken)jason["Status"];
                            JToken barCode = (JToken)jason["Id"];
                            JToken runTime = (JToken)jason["RunTime"];
                            if (runTime == null || runTime.ToString() == "")
                            {
                                break;
                            }
                            string strDay = runTime.ToString();
                            strDay = strDay.Substring(0, strDay.IndexOf("天"));


                            /*if (Convert.ToInt32(strDay) < 4)
                            {
                                continue;
                            }
                            if (status.ToString().Contains("签收") && Convert.ToInt32(strDay) < 8)
                            {
                                continue;
                            }*/
                            if (status != null)
                            {
                                strStatus = status.ToString();
                            }
                            if (runTime != null)
                            {
                                strRunTime = runTime.ToString();
                            }
                            if (barCode != null)
                            {
                                strBarcode = barCode.ToString();
                            }
                            else
                            {
                                continue;
                            }


                            RoadInfo roadInfo = new bean.RoadInfo();
                            roadInfo.runTime = runTime.ToString();
                            roadInfo.wayBillNo = strBarcode;
                            curBarcode = strBarcode;
                            roadInfo.lastScanStatus = strStatus;

                            
                            for (int m = 0; m < jarScanList.Count; m++)
                            {
                                JObject scanInfo = JObject.Parse(jarScanList[m].ToString());
                                string scanType = scanInfo["ScanType"].ToString();
                                string ScanDate = scanInfo["ScanDate"].ToString();
                                string UploadSiteName = scanInfo["UploadSiteName"].ToString();
                                string PreOrNext = scanInfo["PreOrNext"].ToString();
                                string Memo = scanInfo["Memo"].ToString();
                                MemInfo memInfo = new bean.MemInfo();
                                memInfo.memMsg = Memo;
                                memInfo.scanType = scanType;
                                memInfo.scanTime = ScanDate;
                                roadInfo.arListMems.Add(memInfo);
                                if(Memo!=null&&Memo.Contains("快递员取出"))
                                {
                                    roadInfo.isGetOutByDeliver = true;
                                    roadInfo.strErrorMsg = "快件被快递员取出";
                                }

                                if (PreOrNext == StoParams.Instance.register_site && UploadSiteName == StoParams.Instance.arrival_priorSite)
                                {
                                    DateTime dtScanTime = Convert.ToDateTime(ScanDate);
                                    TimeSpan ts = dtScanTime.TimeOfDay;
                                    TimeSpan tsEndTime = DateTime.Parse(StoParams.Instance.arrival_priorSite_SacnEndTime).TimeOfDay;
                                    if (ts < tsEndTime)
                                    {
                                        roadInfo.todayFinish = true;
                                        string strDate = dtScanTime.ToString("yyyy-MM-dd") + " " + "23:59:59";
                                        roadInfo.endLineTime = strDate;
                                    }
                                    roadInfo.arriveSendToSiteTime = ScanDate;
                                }

                                if (scanType.Contains("签收"))
                                {
                                    if (roadInfo.donePackTime.Length > 0)
                                    {
                                        roadInfo.doubleFinished = true;
                                    }
                                    else
                                    {
                                        roadInfo.donePackTime = ScanDate;
                                    }

                                }
                                if (Memo.Contains("派送不成功"))
                                {
                                    break;
                                }
                                if (m == 0)
                                {
                                    roadInfo.lastSiteScanDate = ScanDate;
                                    if (scanType.ToString().Contains("运输中"))
                                    {
                                        roadInfo.lastSiteName = PreOrNext;
                                    }
                                    else
                                    {
                                        roadInfo.lastSiteName = UploadSiteName;
                                    }

                                }
                                if (scanType.ToString().Contains("签收"))
                                {
                                    roadInfo.lastSiteScanDate = "";
                                    if (roadInfo.donePackTime == "")
                                    {
                                        roadInfo.donePackTime = ScanDate;
                                    }
                                }



                                if (scanType.ToString().Contains("派送"))
                                {

                                    UtilityHelp.Instance.fillYizhanOrAssignTime(roadInfo, Memo, ScanDate,scanType);
                                    roadInfo.arrivalBeglongSite = UploadSiteName;

                                }
                                if (scanType.ToString().Contains("运输中"))
                                {
                                    if (roadInfo.arriveSiteTime == "")
                                    {
                                        roadInfo.arriveSiteTime = ScanDate;
                                    }
                                }
                            }
                            if (isArrivalPackDelayed(roadInfo))
                            {
                                arListArriResultTmp.Add(roadInfo.wayBillNo + "," + roadInfo.strErrorMsg + "," + roadInfo.lastSiteName);
                                m_ht_arrival_BarCodes[strBarcode] = roadInfo;
                                //DoneArriAnay.Invoke();
                            }
                        }
                        catch(Exception ex)
                        {

                        }

                    }//for
                    if (priorBarCodeCount != m_ht_arrival_BarCodes.Count)
                    {
                        DateTime dtNow = System.DateTime.Now;
                        TimeSpan ts = dtNow - dtLastRefreshDep;
                        priorBarCodeCount = m_ht_arrival_BarCodes.Count;
                        if (ts.TotalSeconds > 3)
                        {
                            DoneArriAnay.Invoke();
                            DoneArrOrDepAnay();
                        }
                        dtLastRefreshArr = dtNow;
                    }
                    if(totalQueryCount>=200)
                    {
                        ResultBean resultBean = new ResultBean();
                        //resultBean.countTime = totalQueryCount;
                        //resultBean.arList = (ArrayList)arListArriResultTmp.Clone();
                        updateQueryCount(resultBean);
                        totalQueryCount = 0;
                        arListArriResultTmp.Clear();
                    }
                }
                System.Threading.Thread.Sleep(2000);
                DoneArriAnay.Invoke();
                DoneArrOrDepAnay();
                if(totalQueryCount>0)
                {
                    ResultBean resultBean = new ResultBean();
                    //resultBean.countTime = totalQueryCount;
                    //resultBean.arList = (ArrayList)arListArriResultTmp.Clone();
                    updateQueryCount(resultBean);
                    totalQueryCount = 0;
                    arListArriResultTmp.Clear();
                }
                


            }
            catch (Exception ex)
            {
                //System.Windows.Forms.MessageBox.Show("发生异常，条码为"+ curBarcode);
            }
        }




        private bool isDepPackDelayed(RoadInfo roadInfo)
        {
            bool delayed = false;
            if(roadInfo.isChaoPaiPackage)
            {
                delayed = Utility.isChaopaiDelayed(roadInfo);
                if(delayed)
                {
                    roadInfo.strErrorMsg = "超派延误，核对留言";
                    return delayed;
                }
                
            }
            if(StoParams.Instance.isAssignCheck)
            {
                delayed=Utility.isZYCenterDelayed(roadInfo, m_ht_far_province);
            }
            else
            {
                delayed = Utility.isCompanyDelayed(roadInfo,m_ht_far_province);
            }
            

            return delayed;
        }

        public bool isDepTimeExpire(string province,string strRunTime,double defaultDay)
        {
            bool delayed = false;
    
            strRunTime = strRunTime.Replace("天", ".");
            strRunTime = strRunTime.Replace("小时", ":00:00");
            TimeSpan ts = TimeSpan.Parse(strRunTime);
            if (ts.TotalHours > (defaultDay * 24))
            {
                delayed = true;
            }
            return delayed;
        }

        private bool isArrivalPackDelayed(RoadInfo roadInfo)
        {
            bool delayed = false;
            try
            {
                if(roadInfo.isGetOutByDeliver)
                {
                    delayed = true;
                    roadInfo.strErrorMsg = "快件被快递员取出";
                    return delayed;
                }
                if (roadInfo.todayFinish)
                {
                    if (roadInfo.assignPackTime != "")
                    {
                        //判断5.5小时是否有签收或者问题件或者菜鸟驿站
                        DateTime timeAssigh = Convert.ToDateTime(roadInfo.assignPackTime);
                        if (roadInfo.donePackTime == "" && roadInfo.yizhanRecTime == "")//未签收情况
                        {
                            DateTime dtNow = System.DateTime.Now;
                            TimeSpan ts = dtNow - timeAssigh;
                            if(dtNow>Convert.ToDateTime(roadInfo.endLineTime))
                            {
                                roadInfo.strErrorMsg = "当天未签收，已超时";
                                delayed = true;
                                return delayed;
                            }
                            if (ts.TotalMinutes < 330)//5.5小时
                            {
                                delayed = false;
                            }
                            if (ts.TotalMinutes > 330 && ts.TotalMinutes < 360)
                            {
                                double leftMinuts = 360 - ts.TotalMinutes;
                                string strLeft = Math.Ceiling(leftMinuts).ToString();
                                roadInfo.strErrorMsg = "即将超时，还剩" + strLeft + " 分";
                                roadInfo.errorType = 1;
                                delayed = true;
                            }
                            if (ts.TotalMinutes > 360)
                            {
                                double leftMinuts = ts.TotalMinutes - 360;
                                string strLeft = Math.Ceiling(leftMinuts).ToString();
                                roadInfo.strErrorMsg = "已超时，" + strLeft + " 分";
                                roadInfo.errorType = 6;
                                delayed = true;
                            }
                        }//未签收情况

                        else
                        {
                            DateTime dtEndLineTime = Convert.ToDateTime(roadInfo.endLineTime);
                            //已签收情况，判断是否签收超时
                            if (roadInfo.yizhanRecTime != "")
                            {
                                DateTime dtYizhan = Convert.ToDateTime(roadInfo.yizhanRecTime);
                                if (dtEndLineTime < dtYizhan)
                                {
                                    delayed = true;
                                    //驿站签收超时
                                    TimeSpan ts = dtYizhan - dtEndLineTime;
                                    if (ts.Days>0)
                                    {
                                        roadInfo.strErrorMsg = "驿站签收超时" + ts.Days.ToString() + "天" + ts.Hours.ToString() + "小时" + ts.Minutes + "分";
                                    }
                                    else
                                    {
                                        roadInfo.strErrorMsg = "驿站签收超时"  + ts.Hours.ToString() + "小时" + ts.Minutes + "分";
                                    }
                                    
                                }
                                else
                                {
                                    //判断驿站时间是否超时以及7天未取
                                    DateTime dtFinsh = System.DateTime.Now;
                                    if (roadInfo.donePackTime != "")
                                    {
                                        dtFinsh = Convert.ToDateTime(roadInfo.donePackTime);
                                    }
                                    TimeSpan ts = dtFinsh - dtYizhan;
                                    if (ts.TotalDays > 7)
                                    {
                                        delayed = true;
                                        roadInfo.strErrorMsg = "驿站存放" + ts.Days.ToString() + "天" + ts.Hours.ToString() + "小时" + ts.Minutes + "分" + " 超过7天";
                                        roadInfo.errorType = 5;
                                    }

                                }
                            }
                            else
                            {
                                //判断客户直接签收是否超时
                                if (roadInfo.donePackTime != "")
                                {
                                    DateTime dtDone = Convert.ToDateTime(roadInfo.donePackTime);
                                    if (dtDone > dtEndLineTime)
                                    {
                                        delayed = true;
                                        TimeSpan ts = dtDone - dtEndLineTime;
                                        roadInfo.errorType = 3;
                                        if(ts.Days>=1)
                                        {
                                            roadInfo.strErrorMsg = "超时" + ts.Days.ToString() + "天" + ts.Hours.ToString() + "小时" + ts.Minutes + "分";
                                        }
                                        else
                                        {
                                            roadInfo.strErrorMsg = "超时" + ts.Hours.ToString() + "小时" + ts.Minutes + "分";
                                        }
                                       
                                    }
                                }

                            }


                        }
                    }
                    else
                    {
                        //判断当前时间与当日应签收时间间隔，如果大于最晚签收时间，则提示未派件
                        DateTime dtNow = System.DateTime.Now;
                        DateTime dtEndLine = Convert.ToDateTime(roadInfo.endLineTime);
                        if (dtNow > dtEndLine&&roadInfo.yizhanRecTime=="")
                        {
                            delayed = true;
                            roadInfo.errorType = 7;
                            roadInfo.strErrorMsg = "未做派件";
                        }
                    }
                }
                else
                {
                    if (roadInfo.yizhanRecTime != "")
                    {
                        DateTime dtYizhan = Convert.ToDateTime(roadInfo.yizhanRecTime);
                        //判断驿站时间是否超时以及7天未取
                        DateTime dtFinsh = System.DateTime.Now;
                        if (roadInfo.donePackTime != "")
                        {
                            dtFinsh = Convert.ToDateTime(roadInfo.donePackTime);
                        }
                        TimeSpan ts = dtFinsh - dtYizhan;
                        if (ts.TotalDays > 7)
                        {
                            delayed = true;
                            roadInfo.strErrorMsg = "驿站存放时间" + ts.Days.ToString()+"天"+ts.Hours.ToString()+"小时"+ts.Minutes+"分"+ " 超过7天";
                            roadInfo.errorType = 5;
                        }
                    }
                }
                
            }
            catch (Exception ex)
            {

            }

            return delayed;
        }

        
        //SendPost



    }
}
